package cn.antcore.common.authentication.handler;

import cn.antcore.common.exception.ErrorCode;
import cn.antcore.common.exception.ReturnT;
import cn.antcore.common.security.handler.AbstractAuthenticationHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;

/**
 * 处理/userinfo失败响应的结果
 * <br>
 * Created by Hong 2024/5/28
**/
public class UserInfoEndpointFailureHandler extends AbstractAuthenticationHandler implements AuthenticationFailureHandler {

    public UserInfoEndpointFailureHandler(ObjectMapper objectMapper) {
        super(objectMapper);
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        if (exception instanceof OAuth2AuthenticationException oAuth2AuthenticationException) {
            failure(response, ReturnT.fail(new ErrorCode(ErrorCode.ACCESS_TOKEN_ERROR, oAuth2AuthenticationException.getError().toString())));
        } else {
            failure(response, ReturnT.fail(new ErrorCode(ErrorCode.ACCESS_TOKEN_ERROR, exception.getMessage())));
        }
    }
}
